package Thread_Test;

/**
 * 设计4个线程，其中两个线程每次对j增加1，另外两个线程对j每次减少1
 */
public class Thread2_test {
    private int j ;
    public static void main(String[] args){
        Thread2_test thread2_test = new Thread2_test();
        Thread2_test.Dec dec = new Thread2_test().new Dec();//新建内部类两种语法，外部类存在属性，需要用new开辟实例化属性后，才能再对内部类进行实例化
        Inc inc = thread2_test.new Inc();
        //Dec dec = thread2_test.new Dec();//新建内部类两种语法
        for (int i= 0;i<2;i++){
            Thread t = new Thread(inc);
            t.start();
            t=new Thread(dec);
            t.start();
        }
    }
    private synchronized void inc(){
        j++;
        System.out.println(Thread.currentThread().getName()+"-incs:"+j);
    }
    private synchronized void dec(){
        j--;
        System.out.println(Thread.currentThread().getName()+"-dec:"+j);
    }

    class Dec implements Runnable{
        @Override
        public void run() {
            for (int i =0;i<100;i++){
                dec();
            }
        }
    }

    class Inc implements Runnable{
        @Override
        public void run() {
            for (int i = 0;i<100;i++){
                inc();
            }
        }
    }
}
